package link.jfire.disqueue;

import sun.misc.Unsafe;
import link.jfire.baseutil.reflect.ReflectUtil;

@SuppressWarnings("restriction")
public class Sequencer
{
    protected long           p1, p2, p3, p4, p5, p6, p7;
    protected volatile long  cursor;
    protected long           p9, p10, p11, p12, p13, p14, p15;
    public static final long InitValue = -1;
    protected static long    offset    = ReflectUtil.getFieldOffset("cursor", Sequencer.class);
    protected Unsafe         unsafe    = ReflectUtil.getUnsafe();
    private WaitStrategy     waitStrategy;
    
    public long nouse()
    {
        return p1 + p2 + p3 + p4 + p5 + p6 + p7 + cursor + p9 + p10 + p11 + p12 + p13 + p14 + p15;
    }
    
    public long getCursor()
    {
        return cursor;
    }
    
    public void directSet(long cursor)
    {
        this.cursor = cursor;
        waitStrategy.notifyWaiting();
    }
    
    public void casSet(long cursor, long now)
    {
        while (unsafe.compareAndSwapLong(this, offset, now, cursor) == false)
        {
        }
        waitStrategy.notifyWaiting();
    }
    
    public void waitFor(long sequence)
    {
        waitStrategy.waitFor(sequence, this);
    }
}
